package db;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import org.apache.log4j.Logger;
import util.Constants;

public class DbController {
    public static Logger LOG = Logger.getLogger("db.DbController");
    
//  used to obtain data in db.properties
    private static Properties props = new Properties(); 
    static {
        try {
            InputStream is = DbController.class.getResourceAsStream("/db.properties");
            props.load(is);
        } catch (Exception ex) {
            LOG.error("read db.properties file", ex);
        }
    }

//  return a connection
    public static Connection getConnection() {
        try {
            String jdbcDriver = props.getProperty(Constants.JDBC_DRIVER);
            String jdbcUrl = props.getProperty(Constants.JDBC_URL);
            String jdbcUser = props.getProperty(Constants.JDBC_USER);
            String jdbcPassword = props.getProperty(Constants.JDBC_PASSWORD);
            Class.forName(jdbcDriver).newInstance();
            return (Connection) DriverManager.getConnection(jdbcUrl + ";User=" + jdbcUser + ";Password=" + jdbcPassword);
        } catch (Exception ex) {
            LOG.error("getConnection", ex);
            return null;
        }
    }
    // return the root folder of dictionary files
    public static String getDictRootFolder() {
        try {
            return (String) props.getProperty("dictRootFolder");
        } catch (Exception ex) {
            LOG.error("getDictRootFolder", ex);
            return null;
        }
    }

    // for ajax to get n words
    public static int getNumOfNearestWords() {
        try {
            return Integer.parseInt((String) props.getProperty("numOfNearestWords"));
        } catch (Exception ex) {
            LOG.error("getNumOfNearestWords", ex);
            return 0;
        }
    }

    public static int getNumOfLimitedConnection() {
        try {
            return Integer.parseInt((String) props.getProperty("numOfLimitedConnection"));
        } catch (Exception ex) {
            LOG.error("getNumOfLimitedConnection", ex);
            return 1000;
        }
    }
}
